package com.metadata_system.common.http.request_dto;

import com.metadata_system.common.db.entity.User;
import com.metadata_system.common.db.mapper.UserMapper;
import com.metadata_system.common.dto.JwtToken;
import com.metadata_system.common.utils.AesUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 已登录用户-请求参数
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Slf4j
@Service
public class LoginUserRequest {
    Integer userId;
    String token;
    String platform;
    String deviceId;

    // 存储属性键值
    @Value("${metadata-system.token-request-attribute:JWT_TOKEN}")
    private String tokenRequestAttribute = "JWT_TOKEN";

    /**
     * 加载http头部信息
     *
     * @param request
     * @return
     */
    public static LoginUserRequest loadHeaderData(HttpServletRequest request) {
        return LoginUserRequest.builder()
                .deviceId(request.getHeader("DeviceId"))
                .platform(request.getHeader("Platform"))
                .build();
    }

    // 设置 token
    public void setTokenUser(JwtToken jwtToken) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (requestAttributes != null) {
            request = requestAttributes.getRequest();
            request.setAttribute(this.getTokenRequestAttribute(), jwtToken);
        } else {
            log.info("requestAttributes 为空");
        }
    }

    @Autowired(required = false)
    UserMapper userMapper;

    // 获取 token
    public JwtToken getTokenUser() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        // 逻辑工具服务,从header中获取用户名,查询用户信息,生成token
        if (request.getRequestURI().contains("/api/qt-client-server")) {
            User user = this.userMapper.selectOne(User.builder()
                    .username(request.getHeader("Username"))
                    .build());
            if (user == null) {
                return null;
            }
            try {
                return JwtToken.builder()
                        .id( AesUtils.Encrypt(user.getId().toString()))
                        .username(user.getUsername())
                        .role(user.getRole())
                        .build();
            } catch (Exception e) {
                log.error("获取token失败", e);
                return null;
            }

        }

        // 从request中获取token
        Object jwtToken = request.getAttribute(this.getTokenRequestAttribute());
        if (jwtToken == null) {
            throw new SecurityException("当前操作不是登录用户操作");
        }
        return (JwtToken) request.getAttribute(this.getTokenRequestAttribute());
    }


}
